import React, { useState, useEffect } from 'react'
import ReactDOM from 'react-dom'
import { postRegisterXhr, postLoginXhr } from '../api/index'
import toast from '~/utils/toast'
import { setCookie } from '~/utils/cookie'
import { encryptData } from '~/utils/crypto'
interface AuthModalProps {
  isOpen: boolean
  onClose: () => void
  showLogin: boolean
}

const AuthModal: React.FC<AuthModalProps> = ({
  isOpen,
  onClose,
  showLogin = true,
}) => {
  const [isLogin, setIsLogin] = useState(showLogin)
  const [formData, setFormData] = useState({
    username: '',
    password: '',
    confirmPassword: '',
  })
  const [errors, setErrors] = useState({
    username: '',
    password: '',
    confirmPassword: '',
  })
  const [showPassword, setShowPassword] = useState(false)

  useEffect(() => {
    if (isOpen) {
      // 重置表单数据和错误信息
      setFormData({
        username: '',
        password: '',
        confirmPassword: '',
      })
      setErrors({
        username: '',
        password: '',
        confirmPassword: '',
      })
      // 更新 isLogin 状态
      setIsLogin(showLogin)
    }
  }, [isOpen, showLogin])

  const validatePhoneNumber = (phone: string) => {
    const phoneRegex = /^[1-9]\d{10}$/
    return phoneRegex.test(phone)
  }

  const validatePasswordStrength = (password: string) => {
    const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/
    return passwordRegex.test(password)
  }

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    const usernameError = validatePhoneNumber(formData.username)
      ? ''
      : '手机号格式不正确'
    const passwordError = formData.password ? '' : '请输入密码'

    setErrors({
      username: usernameError,
      password: passwordError,
      confirmPassword: '',
    })

    if (!usernameError && !passwordError) {
      try {
        const res = await postLoginXhr({
          username: formData.username,
          password: formData.password,
        })
        if (res?.code === 200) {
          toast.success('登录成功')
          // 加密用户信息后保存
          const encryptedUserInfo = encryptData(res?.data?.userInfo)
          localStorage.setItem('u_info_enc', encryptedUserInfo)

          // 加密token后保存
          const encryptedToken = encryptData(res?.data?.token)
          setCookie('blog_t_enc', encryptedToken, 7) // 7 天有效期

          onClose()
          window.location.reload()
        } else {
          toast.error(`登录失败: ${res?.message}`)
        }
      } catch (error) {
        toast.error('登录失败: 网络错误或服务器未响应')
      }
    }
  }

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault()
    const usernameError = validatePhoneNumber(formData.username)
      ? ''
      : '手机号格式不正确'
    const passwordError = validatePasswordStrength(formData.password)
      ? ''
      : '密码必须至少6位且包含字母和数字'
    const confirmPasswordError =
      formData.password !== formData.confirmPassword
        ? '两次输入的密码不一致'
        : ''

    setErrors({
      username: usernameError,
      password: passwordError,
      confirmPassword: confirmPasswordError,
    })

    if (!usernameError && !passwordError && !confirmPasswordError) {
      try {
        const res = await postRegisterXhr({
          username: formData.username,
          password: formData.password,
        })
        if (res?.code === 200) {
          toast.success('注册成功')
          setIsLogin(true)
          setFormData({
            username: formData.username,
            password: formData.password,
            confirmPassword: '',
          })
        } else {
          toast.error(`注册失败: ${res?.message}`)
        }
      } catch (error) {
        toast.error('注册失败: 网络错误或服务器未响应')
      }
    }
  }

  if (!isOpen) return null

  return ReactDOM.createPortal(
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999]">
      <div className="bg-white dark:bg-gray-800 rounded-lg p-8 w-96 relative z-[10000]">
        <button
          onClick={onClose}
          className="absolute right-4 top-4 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
        >
          <i className="ri-close-line text-xl"></i>
        </button>
        <h2 className="text-2xl font-bold mb-6 text-center">
          {isLogin ? '登录' : '注册'}
        </h2>
        {isLogin ? (
          <form onSubmit={handleLogin} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                手机号
              </label>
              <input
                type="text"
                value={formData.username}
                onChange={(e) =>
                  setFormData({ ...formData, username: e.target.value })
                }
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                required
              />
              {errors.username && (
                <p className="text-red-500 text-xs mt-1">{errors.username}</p>
              )}
            </div>
            <div className="relative">
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                密码
              </label>
              <input
                type={showPassword ? 'text' : 'password'}
                value={formData.password}
                onChange={(e) =>
                  setFormData({ ...formData, password: e.target.value })
                }
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                required
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute right-3 top-8 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
              >
                <i
                  className={showPassword ? 'ri-eye-off-line' : 'ri-eye-line'}
                ></i>
              </button>
              {errors.password && (
                <p className="text-red-500 text-xs mt-1">{errors.password}</p>
              )}
            </div>
            <button
              type="submit"
              className="w-full bg-blue-500 text-white py-2 rounded-lg hover:bg-blue-600 transition-colors"
            >
              登录
            </button>
          </form>
        ) : (
          <form onSubmit={handleRegister} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                手机号
              </label>
              <input
                type="text"
                value={formData.username}
                onChange={(e) =>
                  setFormData({ ...formData, username: e.target.value })
                }
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                required
              />
              {errors.username && (
                <p className="text-red-500 text-xs mt-1">{errors.username}</p>
              )}
            </div>
            <div className="relative">
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                密码
              </label>
              <input
                type={showPassword ? 'text' : 'password'}
                value={formData.password}
                onChange={(e) =>
                  setFormData({ ...formData, password: e.target.value })
                }
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                required
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute right-3 top-8 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
              >
                <i
                  className={showPassword ? 'ri-eye-off-line' : 'ri-eye-line'}
                ></i>
              </button>
              {errors.password && (
                <p className="text-red-500 text-xs mt-1">{errors.password}</p>
              )}
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                确认密码
              </label>
              <input
                type="password"
                value={formData.confirmPassword}
                onChange={(e) =>
                  setFormData({ ...formData, confirmPassword: e.target.value })
                }
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
                required
              />
              {errors.confirmPassword && (
                <p className="text-red-500 text-xs mt-1">
                  {errors.confirmPassword}
                </p>
              )}
            </div>
            <button
              type="submit"
              className="w-full bg-blue-500 text-white py-2 rounded-lg hover:bg-blue-600 transition-colors"
            >
              注册
            </button>
          </form>
        )}
        <div className="mt-4 text-center">
          <button
            onClick={() => setIsLogin(!isLogin)}
            className="text-blue-500 hover:text-blue-600 text-sm"
          >
            {isLogin ? '没有账号？去注册' : '已有账号？去登录'}
          </button>
        </div>
      </div>
    </div>,
    document.body
  )
}

export default AuthModal
